package com.dyz.aspect;

import com.baomidou.mybatisplus.extension.api.IErrorCode;
import com.baomidou.mybatisplus.extension.exceptions.ApiException;
import com.dyz.model.Result;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice // 全局异常处理 Advice 代表是一个切面  RestController 代表处理的是一个JSon
public class GlobalExceptionHandler {
    /**
     * 内部API调用异常处理
     */
    @ExceptionHandler(value = ApiException.class)
    public Result apiExceptionHandler(ApiException apiException) {
        IErrorCode errorCode = apiException.getErrorCode();
        if(errorCode != null){
            return Result.fail(errorCode.getCode(),errorCode.getMsg());
        }
        return Result.fail(apiException.getMessage());
    }

    /**
     * 方法参数校验失败的处理
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        if (bindingResult.hasErrors()) {
            FieldError fieldError = bindingResult.getFieldError();
         if(fieldError != null){
             return Result.fail(fieldError.getField()+fieldError.getDefaultMessage());
         }
        }
        return Result.fail(e.getMessage());
    }
    /**
     * 对像内部使用Validation校验失败的处理
     */
    @ExceptionHandler(value = BindException.class)
    public Result bindExceptionHandler(BindException e) {
        BindingResult bindingResult = e.getBindingResult();
        if (bindingResult.hasErrors()) {
            FieldError fieldError = bindingResult.getFieldError();
            if(fieldError != null){
                return Result.fail(fieldError.getField()+fieldError.getDefaultMessage());
            }
        }
        return Result.fail(e.getMessage());
    }
}
